package com.primaryedu.ui.fragment;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ClearCacheRequest;
import com.android.volley.toolbox.DiskBasedCache;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.emagic.manage.data.entities.response.UserResponse;
import com.emagic.manage.modules.room.activity.RoomActivity;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.primaryedu.R;
import com.primaryedu.adapter.BannerAdapter;
import com.primaryedu.adapter.ExerciseAdapter;
import com.primaryedu.adapter.MainMenuAdapter;
import com.primaryedu.adapter.VideoAdapter;
import com.primaryedu.bean.BannerBean;
import com.primaryedu.bean.ExerciseBean;
import com.primaryedu.bean.FunctionBean;
import com.primaryedu.bean.HomenewsBean;
import com.primaryedu.bean.MicroCourseBean;
import com.primaryedu.bean.NoticeAllBean;
import com.primaryedu.bean.VideoBean;
import com.primaryedu.data.Config;
import com.primaryedu.data.Contants;
import com.primaryedu.data.GlobalData;
import com.primaryedu.data.HigtApplication;
import com.primaryedu.ui.AppCenterActivity;
import com.primaryedu.ui.MainActivity;
import com.primaryedu.ui.app.growstep.GrowStepActivity;
import com.primaryedu.ui.app.messageboard.MessageboardActivity;
import com.primaryedu.ui.app.parentsch.ParentSchoolActivity;
import com.primaryedu.ui.course.CourseDetailActivity;
import com.primaryedu.ui.exercise.ExerciseActivity;
import com.primaryedu.ui.inform.InformActivity;
import com.primaryedu.ui.news.NewsActivity;
import com.primaryedu.utils.Logger;
import com.primaryedu.widget.DragGridViewOlder;
import com.primaryedu.widget.MyGallery;
import com.primaryedu.widget.MyListView;
import com.primaryedu.widget.PullToRefreshView;
import com.primaryedu.widget.PullToRefreshView.OnFooterRefreshListener;
import com.primaryedu.widget.PullToRefreshView.OnHeaderRefreshListener;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Notification;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;

import okhttp3.Call;

/**
 * 首页
 *
 * @author jun.wang
 * @description
 * @data 2016年12月13日
 */
@SuppressLint("NewApi")
public class HomeFragment extends Fragment implements OnClickListener, OnHeaderRefreshListener, OnFooterRefreshListener {
    private View view;
    private MyGallery gallery;
    BannerAdapter adpter;
    private DragGridViewOlder gridView;
    private List<FunctionBean> functionList;
    MainMenuAdapter menuAdapter;
    MyListView newsListView, courseListView;
    //    NewsAdapter newsAdapter ;
    ExerciseAdapter newsAdapter;
    VideoAdapter videoAdapter;
    private TextView text_right;
    protected RequestQueue requestQueue = null;
    private final static int REQUESTCODEINFORM = 2; // "申请"返回的结果码
    private List<ExerciseBean.DataBean.ListBean> newsLists = new ArrayList<>();
    private List<BannerBean> bannerLists = new ArrayList<>();
    private List<MicroCourseBean> courseLists = new ArrayList<>();
    private PullToRefreshView pullToRefreshView;

    private Handler handler = new Handler() {

        public void handleMessage(android.os.Message msg) {

            switch (msg.what) {
                case 1001:
                    if (null != bannerLists && bannerLists.size() != 0) {
                        if (getActivity()!=null) {
                            adpter = new BannerAdapter(getActivity(), bannerLists);
                            gallery.setAdapter(adpter);
                        }
                    }
                    break;

                case 1002:
                    if (null != newsLists && newsLists.size() != 0) {
                        newsAdapter = new ExerciseAdapter(getActivity(), newsLists);
                        newsListView.setAdapter(newsAdapter);
                    }
                    break;

                case 1003:
                    if (null != courseLists && courseLists.size() != 0) {
                        videoAdapter = new VideoAdapter(getActivity(), courseLists);
                        courseListView.setAdapter(videoAdapter);
                    }
                    break;

                default:
                    break;
            }
        }

        ;
    };
    private List<NoticeAllBean.DataBean.ListBean> noticelists = new ArrayList<>();
    private List<NoticeAllBean.DataBean.ListBean> tempnoticeLists = new ArrayList<>();
    private int isRead = 0;
    private HigtApplication application;
    private VideoBean videobean;
    private String serverMessage;
    private String status = "0" ;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_home, container, false);
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        application = (HigtApplication) getActivity().getApplication();
        init();
    }

    private void init() {
        requestQueue = Volley.newRequestQueue(getActivity());

        gallery = (MyGallery) view.findViewById(R.id.gallery);
        ((TextView) view.findViewById(R.id.title)).setText("");
        ((TextView) view.findViewById(R.id.title)).setBackgroundResource(R.drawable.icon_title);
        ;
        view.findViewById(R.id.back).setVisibility(View.GONE);
        view.findViewById(R.id.right).setVisibility(View.VISIBLE);
        text_right = (TextView) view.findViewById(R.id.text_right);
        text_right.setBackgroundResource(R.drawable.icon_inform);
        view.findViewById(R.id.right).setOnClickListener(this);
        view.findViewById(R.id.right).setVisibility(View.GONE);
        view.findViewById(R.id.text_news_more).setOnClickListener(this);
        view.findViewById(R.id.text_course_more).setOnClickListener(this);

        gridView = (DragGridViewOlder) view.findViewById(R.id.gridView);
        newsListView = (MyListView) view.findViewById(R.id.newsListView);
        courseListView = (MyListView) view.findViewById(R.id.courseListView);

        newsListView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                StringBuilder builder = new StringBuilder();
                builder.append(Contants.news_api);
                builder.append(newsLists.get(position).getId() + "/" + GlobalData.getUserId(getActivity()));
                System.out.println("builder==" + builder.toString());
                Intent intent = new Intent(getActivity(), NewsActivity.class);
                intent.putExtra("urlStr", builder.toString());
                intent.putExtra("type", "0");
                intent.putExtra("newId", newsLists.get(position).getId());
                startActivity(intent);
            }
        });

        courseListView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                Intent intent = new Intent(getActivity(), CourseDetailActivity.class);
                intent.putExtra("newId", courseLists.get(position).getId());
                intent.putExtra("type", "1");
                intent.putExtra("videoUrl", courseLists.get(position).getVideourl());
                startActivity(intent);
            }
        });

        pullToRefreshView = (PullToRefreshView) view.findViewById(R.id.main_pull_refresh_view);
        pullToRefreshView.setOnHeaderRefreshListener(this);
        pullToRefreshView.setOnFooterRefreshListener(this);
        pullToRefreshView.setLastUpdated(new Date().toLocaleString());

        initGridData();

        requestBanner();

        requestNews();

        requestCourse();

        requestData();//是否有未读通知

        requestVideo();//是否有视频通话
    }

    private void initGridData() {
        functionList = new ArrayList<>();
        FunctionBean bean = new FunctionBean();
        functionList.add(bean);

        FunctionBean bean2 = new FunctionBean();
        functionList.add(bean2);

        FunctionBean bean3 = new FunctionBean();
        functionList.add(bean3);

        FunctionBean bean4 = new FunctionBean();
        functionList.add(bean4);

        gridView.setItems(functionList);
        menuAdapter = new MainMenuAdapter(getActivity(), isRead,status);
        gridView.setAdapter(menuAdapter);

        gridView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {

                Intent intent = null;
                switch (position) {

                    case 0:
//					intent = new Intent(getActivity(),ExerciseActivity.class) ;
//					intent.putExtra("columnId", "409f2bacb7a64656a755c259d18560fb") ;
//					intent.putExtra("titleStr", "特色文化") ;
//					startActivity(intent);
                        intent = new Intent(getActivity(), AppCenterActivity.class);
                        intent.putExtra("tag", "1");
                        startActivity(intent);
                        break;

                    case 1:
//					intent = new Intent(getActivity(),ExerciseActivity.class) ;
//					intent.putExtra("columnId", "041571030b4f4f5d8acd41de1f09d62d") ;
//					intent.putExtra("titleStr", "校园安全") ;
//					startActivity(intent);

                        intent = new Intent(getActivity(), AppCenterActivity.class);
                        intent.putExtra("tag", "2");
                        startActivity(intent);
                        break;

                    case 2:
                        intent = new Intent(getActivity(), ExerciseActivity.class);
                        intent.putExtra("columnId", "7c0c757481c44d628b5a72aebd00b9fb");
                        intent.putExtra("titleStr", "校园新闻");
                        startActivity(intent);
                        break;

                    case 3://移动办公
//					intent = new Intent(getActivity(),RepairServiceActivity.class) ;
//					startActivity(intent);

                        intent = new Intent(getActivity(), AppCenterActivity.class);
                        intent.putExtra("tag", "3");
                        startActivity(intent);
                        break;

                    case 4://成长脚印
                        intent = new Intent(getActivity(), GrowStepActivity.class);
                        startActivity(intent);
//					Toast.makeText(getActivity(), "暂未开通，敬请期待！", Toast.LENGTH_SHORT).show() ;
                        break;

                    case 5://通知公告
                        intent = new Intent(getActivity(), InformActivity.class);
                        startActivityForResult(intent, REQUESTCODEINFORM);
                        break;

                    case 6://家校互动
                        if (GlobalData.getUsertype(getActivity()).contains("3")
                                || GlobalData.getUsertype(getActivity()).contains("4")
                                || GlobalData.getUsertype(getActivity()).contains("7")) {
                            intent = new Intent(getActivity(), ParentSchoolActivity.class);  // 首页直接进去
                            intent.putExtra("tag", "4");
                            startActivity(intent);
                        } else {
                            Toast.makeText(getActivity(), "当前角色不可使用！", Toast.LENGTH_SHORT).show();
                        }
                        break;
                    case 7://留言板
                        intent = new Intent(getActivity(), MessageboardActivity.class);
                        startActivity(intent);
                        break;
                    case 8://家校视频
                        getUserselect();

                        break;
                    default:
                        break;
                }

            }
        });
    }

    private void getUserselect() {
        String url = "https://njtx.njtxqxx.com/rest/user/getUseridSelectUser";
        Map<String, String> params = new HashMap<>();
        System.out.println("id==" + GlobalData.getUserId(getActivity()));
        params.put("id",GlobalData.getUserId(getActivity()) );
        OkHttpUtils.post()//
                .url(url)
                .params(params)
                .build()//
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        System.out.println("responseVideoinHomefragment==" + response);
                        Gson gson = new Gson();
                        videobean = gson.fromJson(response, VideoBean.class);
                        int result = videobean.getResult();
                        if (result == 1) {
//                                    serverMessage = "YES!";
                            serverMessage = videobean.getData().getList().get(0).getStatus();
                            Log.i("yy","status======" + serverMessage);
                            if ("1".equals(serverMessage)) {
                                UserResponse userResponse = new UserResponse();
                                userResponse.setUserid(GlobalData.getUserId(getActivity()));
                                userResponse.setUserroleid("2");//用户角色 0：主讲 1：助教 2: 学员 3：直播用户 4:巡检员　10:系统管理员　11:平台管理员　12:企业管理员 14:二级代理
                                userResponse.setFirstname(GlobalData.getUserId(getActivity()));
                                application.setCurrentUser(userResponse);
                                if (GlobalData.getSerial(getActivity()) != null)
                                    RoomActivity.toAction(getActivity(),
                                            GlobalData.getSerial(getActivity()),
                                            "",
                                            "铁心桥小学",
                                            "0");
                            }else if ("0".equals(serverMessage)){
                                Toast.makeText(getActivity(), "暂无视频通话！", Toast.LENGTH_SHORT).show();
                            }
                        }

                    }
                });
    }

    @Override
    public void onClick(View v) {
        Intent intent = null;

        switch (v.getId()) {
            case R.id.right:
                intent = new Intent(getActivity(), InformActivity.class);
                startActivity(intent);
                break;

            case R.id.text_news_more:
                Config.towardIndex = 2;
                intent = new Intent(getActivity(), MainActivity.class);
                startActivity(intent);
                break;

            case R.id.text_course_more:
                Config.towardIndex = 3;
                intent = new Intent(getActivity(), MainActivity.class);
                startActivity(intent);
                break;

            default:
                break;
        }
    }

    private void requestCourse() {
        Map<String, String> params = new HashMap<String, String>();
        params.put("pageSize", "2");
        OkHttpUtils.post()//
                .url(Contants.getCourse)
                .params(params)//
                .build()//
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        System.out.println("response==getCourse==" + response);

                        try {
                            JSONObject json = new JSONObject(response);
                            int result = json.getInt("result");

                            if (result == 1) {
                                String data = json.getString("data");
                                JSONObject listObj = new JSONObject(data);
                                String listStr = listObj.getString("list");

                                courseLists = new Gson().fromJson(listStr,
                                        new TypeToken<List<MicroCourseBean>>() {
                                        }.getType());
                                handler.sendEmptyMessage(1003);
                                System.out.println("bannerLists==" + courseLists);
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    private void requestBanner() {
        Map<String, String> params = new HashMap<String, String>();
        params.put("type", "app");
        OkHttpUtils.post()//
                .url(Contants.getBanner)
                .params(params)//
                .build()//
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        System.out.println("response==getBanner==" + response);

                        try {
                            JSONObject json = new JSONObject(response);
                            int result = json.getInt("result");

                            if (result == 1) {
                                String data = json.getString("data");
                                bannerLists = new Gson().fromJson(data,
                                        new TypeToken<List<BannerBean>>() {
                                        }.getType());
                                handler.sendEmptyMessage(1001);
                                System.out.println("bannerLists==" + bannerLists);
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    private void requestNews() {
        Map<String, String> params = new HashMap<String, String>();
        params.put("status", "1");
        params.put("pageSize", "2");
        OkHttpUtils.post()//
                .url(Contants.getNews)
                .params(params)//
                .build()//
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        System.out.println("newsresponse==homenews===" + response);

                        try {
                            JSONObject json = new JSONObject(response);
                            int result = json.getInt("result");

                            if (result == 1) {
                                String data = json.getString("data");
                                JSONObject listObj = new JSONObject(data);
                                String listStr = listObj.getString("list");

                                newsLists = new Gson().fromJson(listStr,
                                        new TypeToken<List<ExerciseBean.DataBean.ListBean>>() {
                                        }.getType());
                                handler.sendEmptyMessage(1002);
                                System.out.println("newsLists==" + listStr);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    private void requestData() {
        Map<String, String> params = new HashMap<String, String>();
        params.put("pageSize", "50");
        params.put("pageNo", "1");
        params.put("userid", GlobalData.getUserId(getActivity().getApplicationContext()));
        OkHttpUtils.post()//
                .url(Contants.getNotice)
                .params(params)//
                .build()//
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        System.out.println("getNotice==" + response);

                        try {
                            JSONObject json = new JSONObject(response);
                            int result = json.getInt("result");

                            if (result == 1) {
                                String data = json.getString("data");
                                JSONObject listObj = new JSONObject(data);
                                String listStr = listObj.getString("list");
                                String count = listObj.getString("count");
                                int size = Integer.parseInt(count);

                                noticelists = new Gson().fromJson(listStr,
                                        new TypeToken<List<NoticeAllBean.DataBean.ListBean>>() {
                                        }.getType());
                                isRead = 0;
                                for (int i = 0; i < size; i++) {
                                    NoticeAllBean.DataBean.ListBean nb = noticelists.get(i);
                                    Log.i("yy", "nb.getIfread()=========" + nb.getIfread());
                                    if (nb.getIfread().equals("0")) {
                                        isRead++;
                                        //有未读的通知时
                                    }
                                    Log.i("yy", "isRead=======" + nb.getIfread());
                                    Logger.withTag("yy").log("ISREAD====" + nb.getIfread());
                                    menuAdapter = new MainMenuAdapter(getActivity(), isRead,status);
                                    gridView.setAdapter(menuAdapter);
                                }
                                System.out.println("getNotice==" + listStr);
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    public void requestVideo(){
        Map<String, String> params = new HashMap<String, String>();
        params.put("id", GlobalData.getUserId(getActivity().getApplicationContext()));
        OkHttpUtils.post()//
                .url(Contants.getVideoinfo)
                .params(params)//
                .build()//
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        System.out.println("getVideoinfo==" + response);
                        Gson gson = new Gson();
                        videobean = gson.fromJson(response, VideoBean.class);
                        int result = videobean.getResult();
                        if (result == 1) {
//                                    serverMessage = "YES!";
                            status = videobean.getData().getList().get(0).getStatus();
                            Log.i("yy","status======" + status);
                            menuAdapter = new MainMenuAdapter(getActivity(), isRead,status);
                            gridView.setAdapter(menuAdapter);
                        }
//                        try {
//                            JSONObject json = new JSONObject(response);
//                            int result = json.getInt("result");
//
//                            if (result == 1) {
//                                String data = json.getString("data");
//                                JSONObject listObj = new JSONObject(data);
//                                String listStr = listObj.getString("list");
//                                String count = listObj.getString("count");
//                                int size = Integer.parseInt(count);
//
//                                noticelists = new Gson().fromJson(listStr,
//                                        new TypeToken<List<NoticeAllBean.DataBean.ListBean>>() {
//                                        }.getType());
//                                isRead = 0;
//                                for (int i = 0; i < size; i++) {
//                                    NoticeAllBean.DataBean.ListBean nb = noticelists.get(i);
//                                    Log.i("yy", "nb.getIfread()=========" + nb.getIfread());
//                                    if (nb.getIfread().equals("0")) {
//                                        isRead++;
//                                        //有未读的通知时
//                                    }
//                                    Log.i("yy", "isRead=======" + nb.getIfread());
//                                    Logger.withTag("yy").log("ISREAD====" + nb.getIfread());
//                                    menuAdapter = new MainMenuAdapter(getActivity(), isRead);
//                                    gridView.setAdapter(menuAdapter);
//                                }
//                                System.out.println("getNotice==" + listStr);
//                            }

//                        } catch (JSONException e) {
//                            e.printStackTrace();
//                        }
                    }
                });
    }

    @Override
    public void onFooterRefresh(PullToRefreshView view) {
        pullToRefreshView.postDelayed(new Runnable() {

            @Override
            public void run() {
                pullToRefreshView.onFooterRefreshComplete();
            }

        }, 1500);
    }

    @Override
    public void onHeaderRefresh(PullToRefreshView view) {
        pullToRefreshView.postDelayed(new Runnable() {
            @Override
            public void run() {
                requestNews();
                requestVideo();
                requestCourse();
                requestData();
                pullToRefreshView.onHeaderRefreshComplete("更新于:"
                        + Calendar.getInstance().getTime().toLocaleString());
                pullToRefreshView.onHeaderRefreshComplete();
                Toast.makeText(getActivity(), "数据刷新完成!", Toast.LENGTH_SHORT).show();
            }

        }, 1500);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // RESULT_OK，判断另外一个activity已经结束数据输入功能，Standard activity result:
        // operation succeeded. 默认值是-1
        if (resultCode == 3) {
            if (requestCode == REQUESTCODEINFORM) {
                requestData();
            }
        }
    }
}
